package com.lc.stock.module.crawldata.impl;

import com.alibaba.fastjson.JSONObject;
import com.lc.stock.common.CrawDataAPI;
import com.lc.stock.module.companyinfo.dao.CompanyInfoDao;
import com.lc.stock.module.companyinfo.domain.CompanyInfo;
import com.lc.stock.module.crawldata.AbstractCrawData;
import com.lc.stock.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lichen
 * @description 爬取公司信息（CompanyInfo）数据
 * @menu
 * @date 2023/2/7 8:26
 */
@Slf4j
@Service
public class CrawCompyIfService extends AbstractCrawData {

    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private CompanyInfoDao companyInfoDao;

    /**
     * 爬取公司信息数据
     * @param stockCode
     */
    @Override
    public void doCraw(String stockCode) {
        try{
            //查询公司数据
            String resp = httpClientUtil.get(CrawDataAPI.COMPANY_INFO.getUrl(), stockCode);
            CompanyInfo companyInfo = JSONObject.parseObject(resp, CompanyInfo.class);
            companyInfo.setStockCode(stockCode);

            //保存、更新数据库
            CompanyInfo byStockCode = companyInfoDao.findByStockCode(stockCode);
            if(null != byStockCode){
                companyInfo.set_id(byStockCode.get_id());
            }
            companyInfoDao.save(companyInfo);
        }catch(Exception e){
            log.error("抓取公司信息数据失败:" + stockCode,e);
        }
    }

    @Override
    public String getSubClassName() {
        return this.getClass().getName();
    }
}
